package com.road7.mina.customCodec.protobuf;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoderAdapter;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;

import com.road.yishi.pb.active.StudentMsgProto;
import com.road.yishi.pb.active.StudentMsgProto.StudentRspMsg;

/**
 * @Description :
 * @FileName: ProtobufStrictEncoder.java
 * @Author :WeiHui.Zhang
 * @Data : 2015年11月20日 上午9:13:01
 * @Version:V1.00
 */
public class ProtobufStrictEncoder extends ProtocolEncoderAdapter {

	@Override
	public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception {
		// PBMessage pbMessage = (PBMessage) message;
		//
		// int code = pbMessage.getCode();
		//
		// System.out.println(code);
		//
		// int size = PBMessage.HDR_SIZE;
		// Message msg = pbMessage.getMessage();
		// if (msg != null) {
		// size = PBMessage.HDR_SIZE + msg.getSerializedSize(); // 数据长度
		// }
		// IoBuffer buffer = IoBuffer.allocate(size);
		//
		// pbMessage.writeHeader(size, buffer); // 协议头部
		//
		// out.write(buffer);

		StudentMsgProto.StudentRspMsg studentRspMsg = (StudentRspMsg) message;

		byte[] byteArray = studentRspMsg.toByteArray();// Student对象转为protobuf字节码

		int length = byteArray.length;

		IoBuffer buffer = IoBuffer.allocate(length + 4);
		buffer.putInt(length); // write header
		buffer.put(byteArray); // write body
		buffer.flip();
		out.write(buffer);
	}

}
